package com.sisyphus.mock;

import android.app.Application;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.sisyphus.mock.data.AppDatabase;
import com.sisyphus.mock.utils.NetUtils;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.net.InetAddress;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import androidx.annotation.Nullable;

public class MockApplicationServer extends Service {

    public static Application sApplication;

    public static void startServer(Application application) {
        sApplication = application;
        Intent intent = new Intent(application, MockApplicationServer.class);
        application.startService(intent);
    }

    public static String getHostAddress() {
        InetAddress address = NetUtils.getLocalIPAddress();
        return "http://" + Objects.requireNonNull(address).getHostAddress() + ":8080";
    }


    private Server mServer;

    @Override
    public void onCreate() {
        super.onCreate();

        // 数据库
        AppDatabase.register(getApplicationContext());

        mServer = AndServer.webServer(this)
                .port(8080)
                .timeout(10, TimeUnit.SECONDS)
                .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mServer.startup();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        mServer.shutdown();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
